import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'data_provider.dart';
import 'product.dart';

/// 主屏幕：展示商品列表
class PerformanceOptimizedScreen extends StatelessWidget {
  const PerformanceOptimizedScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final dataProvider = Provider.of<DataProvider>(context);

    return Scaffold(
      appBar: AppBar(title: const Text('商品列表')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: dataProvider.products.length + 1, // 包括加载更多项
              itemBuilder: (context, index) {
                if (index == dataProvider.products.length) {
                  // 构建加载提示或完成消息
                  return dataProvider.hasMore
                      ? const Padding(
                          padding: EdgeInsets.all(16.0),
                          child: Center(child: CircularProgressIndicator()),
                        )
                      : const Padding(
                          padding: EdgeInsets.all(16.0),
                          child: Center(child: Text('没有更多商品了')),
                        );
                }

                // 构建商品信息项
                return _buildProductItem(dataProvider.products[index]);
              },
            ),
          ),
          if (dataProvider.isLoading) Container(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: dataProvider.loadNextPage, // 手动触发加载更多
        child: const Icon(Icons.add),
      ),
    );
  }

  /// 构建商品列表项
  Widget _buildProductItem(Product product) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
      elevation: 5,
      shadowColor: Colors.grey.withOpacity(0.2), // 设置阴影颜色
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10), // 圆角效果
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              product.name,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8.0),
            Text(
              '价格：¥${product.price.toStringAsFixed(2)}',
              style: const TextStyle(fontSize: 16, color: Colors.green),
            ),
            const SizedBox(height: 8.0),
            Text(
              product.description,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
